import axios from 'axios'
import qs from 'qs'
import config from './config'
import router from '../../router'
import { showMsg, getStorage } from '@/assets/js/utils.js'
import { hideLoading } from '@/assets/js/loading'
// import { getStorage, setStorage, removeStorage } from '../assets/js/utils'

// axios.defaults.timeout = 6000
axios.defaults.timeout = 60000
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.headers.get['Content-Type'] = 'application/json';
axios.defaults.baseURL = config.baseApi
// axios.defaults.withCredentials = true

// axios兼容IE 8-9
axios.interceptors.response.use((response) => {
    // IE 8-9
    if (
        response.data == null &&
        response.config.responseType === 'json' &&
        response.request.responseText != null
    ) {
        try {
            // eslint-disable-next-line no-param-reassign
            response.data = JSON.parse(response.request.responseText)
        } catch (e) {
            // ignored
        }
    }
    return response
})
function request(options) {
    let dataParams = options.data
    let data = {}
    let requestUrl = options.url
    options.method = options.method || 'get'

    for (let key in dataParams) {
        data[key] = dataParams[key]
    }

    if (options.method.toLowerCase() === 'get') {
        data = qs.stringify(data)
        if (data.length > 0) {
            requestUrl += requestUrl.indexOf('?') >= 0 ? '&' : '?'
            requestUrl += data
        }
    }
    axios.interceptors.request.use(
        function (config) {
            let token = getStorage('gateway_token')
            if (token) {
                config.headers.Authorization = 'Bearer ' + token
            }
            return config
        },
        function (err) {
            return Promise.reject(err)
        }
    )

    return new Promise(function (resolve, reject) {
        axios({
            url: requestUrl,
            method: options.method,
            responseType: options.responseType || 'json',
            data: data,
        })
            .then((res) => {
                setTimeout(() => {
                    hideLoading()
                }, 200)
                if (res.data.code == '401') {
                    router.replace('/login')
                    reject(res.data)
                } else if (res.data.code == 0) {
                    resolve(res.data)
                } else {
                    showMsg(res.data.msg || '系统错误', 'error')
                    reject(res.data)
                }
            })
            .catch((error) => {
                setTimeout(() => {
                    hideLoading()
                }, 200)
                if (error.response) {
                    if (error.response.status == '401') {
                        router.replace('/login')
                    } else {
                        showMsg(error.response.data.msg || '系统错误', 'error')
                        reject(error.response.data)
                    }
                } else {
                    // console.log(error.request)
                    // console.log(error.msg)
                    showMsg(error.msg || '系统错误', 'error')
                    reject({ msg: error.msg })
                }
            })
    })
}

function get(url, params) {
    return request({
        method: 'GET',
        url: url,
        data: params,
    })
}
function post(url, params) {
    return request({
        method: 'POST',
        url: url,
        data: params,
    })
}
function del(url, params) {
    return request({
        method: 'DELETE',
        url: url,
        data: params,
    })
}
export { request, axios, get, post, del }
